package pl.plesken.xml;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.NoSuchElementException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;


public class ConfigXML {
	LinkedList<String> row = new LinkedList<String>();
	LinkedList<String> save = new LinkedList<String>();
	StringBuffer str = new StringBuffer();
	StringBuffer xml = new StringBuffer();
	
	
	public LinkedList<String> getRow() {
		return row;
	}

	public void setRow(LinkedList<String> row) {
		this.row = row;
	}

	public LinkedList<String> getSave() {
		return save;
	}

	public void setSave(LinkedList<String> save) {
		this.save = save;
	}


	public void parseConfXML() {
		try {
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File("conf" + File.separator + "hosts.xml"));
            
            doc.getDocumentElement().normalize ();
            
            NodeList listOfHosts = doc.getElementsByTagName("host");     

            row.clear();
            
            for(int s = 0; s < listOfHosts.getLength() ; s++) {
            	Node HostNode = listOfHosts.item(s);
                if(HostNode.getNodeType() == Node.ELEMENT_NODE){
                	Element HostElement = (Element)HostNode;
                	
                	NodeList NameList = HostElement.getElementsByTagName("name");
                    Element NameElement = (Element)NameList.item(0);

                    NodeList nameFNList = NameElement.getChildNodes();
                    if (nameFNList.getLength() > 0) {
                   		str.append(((Node)nameFNList.item(0)).getNodeValue().trim());
                	} else {
                		str.append("empty");
                	}
 
                	NodeList srcpathList = HostElement.getElementsByTagName("srcpath");
                    Element srcpathElement = (Element)srcpathList.item(0);

                    NodeList srcpathFNList = srcpathElement.getChildNodes();
                    if (srcpathFNList.getLength() > 0) {
                    	str.append(";" + ((Node)srcpathFNList.item(0)).getNodeValue().trim());
                	} else {
                		str.append(";empty");
                	}
                   	
                	NodeList nmtpathList = HostElement.getElementsByTagName("nmtpath");
                    Element dstpathElement = (Element)nmtpathList.item(0);

                    NodeList nmtpathFNList = dstpathElement.getChildNodes();
                    if (nmtpathFNList.getLength() > 0) {
                    	str.append(";" + ((Node)nmtpathFNList.item(0)).getNodeValue().trim());
                	} else {
                		str.append(";empty");
                	}

                   	NodeList exlList = HostElement.getElementsByTagName("exclude");
                    Element exlElement = (Element)exlList.item(0);

                    NodeList exlFNList = exlElement.getChildNodes();
                    if (exlFNList.getLength() > 0) {
                    	str.append(";" + ((Node)exlFNList.item(0)).getNodeValue().trim());
                	} else {
                		str.append(";empty");
                	}
                   	
                   	NodeList sgnList = HostElement.getElementsByTagName("sign");
                    Element sgnElement = (Element)sgnList.item(0);

                    NodeList sgnFNList = sgnElement.getChildNodes();
                    if (sgnFNList.getLength() > 0) {
                    	str.append(";" + ((Node)sgnFNList.item(0)).getNodeValue().trim());
                	} else {
                		str.append(";empty");
                	}
                   	
                   	NodeList statList = HostElement.getElementsByTagName("status");
                    Element statElement = (Element)statList.item(0);

                    NodeList statFNList = statElement.getChildNodes();
                    if (statFNList.getLength() > 0) {
                    	str.append(";" + ((Node)statFNList.item(0)).getNodeValue().trim());
                	} else {
                		str.append(";empty");
                	}
                   	
                   	row.add(str.toString());
                   	str.setLength(0);
                }
            }

		} catch(SAXParseException err) {
			
		} catch(SAXException e) {
			
		} catch(Throwable t) {
			t.printStackTrace();
		}

	}
	
	public void saveConfXML() {
		try {
			FileOutputStream cfg = new FileOutputStream("conf" + File.separator + "hosts.xml"); //$NON-NLS-1$
			BufferedWriter cfgxml = new BufferedWriter(new OutputStreamWriter(cfg));
			
			xml.setLength(0);
			
			xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + 					
					   "<!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\">\n" +
					   "<hosts>\n");
			//System.out.println(save.size());
			
			for (int i = 0; i < save.size(); i++) {
				//System.out.println("list: " + save.get(i).toString());
				String[] tab = save.get(i).split(";");
				if (!tab[0].toString().equals("null")) {
					xml.append("  <host>\n");
					if (tab[0].toString().equals("empty")) {
						xml.append("    <name></name>\n");
					} else {
						xml.append("    <name>" + tab[0].toString() + "</name>\n");
					}
					if (tab[1].toString().equals("empty")){
						xml.append("    <srcpath></srcpath>\n");
					} else {
						xml.append("    <srcpath>" + tab[1].toString() + "</srcpath>\n");
					}
					if (tab[2].toString().equals("empty")) {
						xml.append("    <nmtpath></nmtpath>\n");
					} else {
						xml.append("    <nmtpath>" + tab[2].toString() + "</nmtpath>\n");
					}
					if (tab[3].toString().equals("empty")) {
						xml.append("    <exclude></exclude>\n");
					} else {
						xml.append("    <exclude>" + tab[3].toString() + "</exclude>\n");
					}
					if (tab[4].toString().equals("empty")) {
						xml.append("    <sign></sign>\n");
					} else {
						xml.append("    <sign>" + tab[4].toString() + "</sign>\n");
					}
					if (tab[5].toString().equals("empty")) {
						xml.append("    <status></status>\n");
					} else {
						xml.append("    <status>" + tab[5].toString() + "</status>\n");
					}
					xml.append("  </host>\n");
					//System.out.println(tab[5]);
				}
			}

			xml.append("</hosts>\n");
			
			cfgxml.write(xml.toString());
			cfgxml.close();
			save.clear();
			//System.out.println("wielkosc " + save.size());
		} catch(FileNotFoundException e) {
			
		} catch(IOException e) {
			
		} catch(NoSuchElementException e) {
			
		}
	}
	
	public void parseCategoriesXML() {
		try {
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File("categories.xml"));
            
            doc.getDocumentElement().normalize ();
            
            NodeList listOfCategory = doc.getElementsByTagName("category");

            row.clear();
            
            for(int s = 0; s < listOfCategory.getLength() ; s++) {
            	Node CategoryNode = listOfCategory.item(s);
            	
            	if (CategoryNode.getAttributes().getLength() > 0) {
            		str.append(CategoryNode.getAttributes().item(0).getNodeValue());
            	} else {
            		str.append("empty");
            	}
            	 			
                if(CategoryNode.getNodeType() == Node.ELEMENT_NODE){
                	
                	Element CategoryElement = (Element)CategoryNode;
                	
                	NodeList status = CategoryElement.getElementsByTagName("enable");
                    Element statusElement = (Element)status.item(0);

                    NodeList statusFNList = statusElement.getChildNodes();
                    if (statusFNList.getLength() > 0) {
                   		str.append(";" + ((Node)statusFNList.item(0)).getNodeValue().trim());
                	} else {
                		str.append(";empty");
                	}
 
                	NodeList rename = CategoryElement.getElementsByTagName("rename");
                    Element renameElement = (Element)rename.item(0);

                    NodeList renameFNList = renameElement.getChildNodes();
                    if (renameFNList.getLength() > 0) {
                    	str.append(";" + ((Node)renameFNList.item(0)).getNodeValue().trim());
                	} else {
                		str.append(";empty");
                	}

                   	row.add(str.toString());
                   	str.setLength(0);
                }
            }

		} catch(SAXParseException err) {
			
		} catch(SAXException e) {
			
		} catch(Throwable t) {
			t.printStackTrace();
		}

	}
	
	public void saveCategoriesXML() {
		try {
			FileOutputStream cfg = new FileOutputStream("categories.xml"); //$NON-NLS-1$
			BufferedWriter cfgxml = new BufferedWriter(new OutputStreamWriter(cfg));
			
			xml.setLength(0);
			
			xml.append("<categories>\n");
			
			for (int i = 0; i < save.size(); i++) {
				String[] tab = save.get(i).split(";");
				if (!tab[0].toString().equals("null")) {
					if (tab[0].toString().equals("empty")) {
						xml.append("  <category name=\"\">\n");
					} else {
						xml.append("  <category name=\"" + tab[0].toString() + "\">\n");
					}
					if (tab[2].toString().equals("empty")){
						xml.append("    <enable>false</enable>\n");
					} else {
						xml.append("    <enable>" + tab[2].toString() + "</enable>\n");
					}
					if (tab[1].toString().equals("empty")) {
						xml.append("    <rename></rename>\n");
					} else {
						xml.append("    <rename>" + tab[1].toString() + "</rename>\n");
					}
					xml.append("  </category>\n");
				}
			}

			xml.append("</categories>\n");
			
			cfgxml.write(xml.toString());
			cfgxml.close();
			save.clear();

		} catch(FileNotFoundException e) {
			
		} catch(IOException e) {
			
		} catch(NoSuchElementException e) {
			
		}
	}
	
	public void parseGenresXML() {
		try {
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File("genres.xml"));
            
            doc.getDocumentElement().normalize ();
            
            NodeList listOfGenres = doc.getElementsByTagName("genre");

            row.clear();
            
            for(int s = 0; s < listOfGenres.getLength() ; s++) {
            	Node GenreNode = listOfGenres.item(s);
            	
            	if (GenreNode.getAttributes().getLength() > 0) {
            		str.append(GenreNode.getAttributes().item(0).getNodeValue());
            	} else {
            		str.append("empty");
            	}
            	
            	if(GenreNode.getNodeType() == Node.ELEMENT_NODE) {          		
            		Element GenreElement = (Element)GenreNode;
                	          	
            		for (int i = 0; i < GenreElement.getElementsByTagName("subgenre").getLength(); i++) {
                        if (GenreElement.getElementsByTagName("subgenre").getLength() > 0) {
                       		str.append(";" + GenreElement.getElementsByTagName("subgenre").item(i).getChildNodes().item(0).getNodeValue().trim());
                    	} else {
                    		str.append(";empty");
                    	}
            		}
            	}
            	
            	row.add(str.toString());
            	str.setLength(0);
            }

		} catch(SAXParseException err) {
			
		} catch(SAXException e) {
			
		} catch(Throwable t) {
			t.printStackTrace();
		}

	}
	
	public void saveGenresXML() {
		try {
			FileOutputStream cfg = new FileOutputStream("genres.xml"); //$NON-NLS-1$
			BufferedWriter cfgxml = new BufferedWriter(new OutputStreamWriter(cfg));
			
			xml.setLength(0);
			
			xml.append("<genres>\n");
			for (int i = 0; i < save.size(); i++) {
				String[] tab = save.get(i).split(";");
				xml.append("  <genre name=\"" + tab[0].toString() + "\">\n");
				for (int s = 1; s < tab.length; s++) {
					xml.append("    <subgenre>" + tab[s].toString() + "</subgenre>\n");
				}
				xml.append("  </genre>\n");
			}

			xml.append("</genres>\n");
			
			cfgxml.write(xml.toString());
			cfgxml.close();
			save.clear();

		} catch(FileNotFoundException e) {
			
		} catch(IOException e) {
			
		} catch(NoSuchElementException e) {
			
		}
	}
	
}